package com.vilinno.tlias.aspect;

import com.vilinno.tlias.mapper.OperateLogMapper;
import com.vilinno.tlias.pojo.OperateLog;
import com.vilinno.tlias.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("execution(* com.vilinno.tlias.controller.*.add(..))||" +
            "execution(* com.vilinno.tlias.controller.*.delete(..))||"+
            "execution(* com.vilinno.tlias.controller.*.update(..))")
    public Object logOperate(ProceedingJoinPoint joinPoint) throws Throwable {
        //预处理 记录时间
        long start=System.currentTimeMillis();


        //执行连接点方法
        Object result=joinPoint.proceed();

        //后处理 记录结束时间
        long end=System.currentTimeMillis();
        long costTime=end-start;

        //记录签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        //构建日志
        OperateLog operateLog=new OperateLog();
        operateLog.setOperateEmpId(getCurrentUserId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setCostTime(costTime);
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        operateLog.setReturnValue(result==null?"void":result.toString());

        log.info("生成操作日志：{}",operateLog);
        operateLogMapper.insert(operateLog);

        return result;
    }

    private Integer getCurrentUserId(){
        return CurrentHolder.getCurrentId();
    }

}
